<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>扑克牌游戏</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .card {
            display: inline-block;
            width: 60px;
            height: 90px;
            border: 1px solid #ccc;
            margin: 5px;
            text-align: center;
            line-height: 90px;
            background: white;
            border-radius: 5px;
            font-weight: bold;
        }
        .card.hearts, .card.diamonds {
            color: #ff0000 !important;
        }
        .card.clubs, .card.spades {
            color: #000000 !important;
        }
        .player {
            margin: 20px 0;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 5px;
        }
        .dealer {
            background-color: #fff3cd;
        }
        .farmer {
            background-color: #e9ecef;
        }
        .current-player {
            border: 2px solid #007bff;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
        }
        button:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
        #gameState {
            margin: 20px 0;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        #roomInfo {
            margin: 10px 0;
            padding: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
        }
        .error {
            color: #dc3545;
            margin: 10px 0;
            padding: 10px;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 5px;
            display: none;
        }
        #loginSection {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        #loginSection input {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }
        #gameSection {
            display: none;
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        .card-back {
            background: linear-gradient(45deg, #1a237e, #0d47a1);
            border: 1px solid #0d47a1;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .card-back-inner {
            width: 100%;
            height: 100%;
            background: repeating-linear-gradient(
                45deg,
                #1a237e,
                #1a237e 10px,
                #0d47a1 10px,
                #0d47a1 20px
            );
        }
        .turn-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.9em;
            margin-left: 10px;
        }
        .turn-status.active {
            background-color: #4caf50;
            color: white;
        }
        .turn-status.completed {
            background-color: #9e9e9e;
            color: white;
        }
        .winner-tag {
            display: inline-block;
            padding: 4px 8px;
            background-color: #ffd700;
            color: #000;
            border-radius: 4px;
            margin-left: 10px;
            font-weight: bold;
            animation: winner-pulse 2s infinite;
        }
        @keyframes winner-pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        .points, .card-count {
            margin-top: 10px;
            font-weight: bold;
        }
        .draw-btn {
            margin-top: 10px;
            padding: 8px 16px;
            background-color: #4caf50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .draw-btn:hover {
            background-color: #45a049;
        }
        .draw-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>扑克牌游戏</h1>
        
        <div id="loginSection">
            <input type="text" id="playerName" placeholder="输入你的名字">
            <button onclick="createRoom()">创建房间</button>
            <input type="text" id="roomId" placeholder="输入房间ID">
            <button onclick="joinRoom()">加入房间</button>
            <div id="error" class="error"></div>
        </div>

        <div id="gameSection">
            <div id="roomInfo"></div>
            <div id="gameState"></div>
            
            <div id="players"></div>
            
            <div id="controls">
                <button id="startGameBtn" onclick="startGame()" style="display: none;">开始游戏</button>
                <button id="becomeDealerBtn" onclick="becomeDealer()" style="display: none;">抢庄</button>
                <button id="drawCardBtn" onclick="drawCard()" style="display: none;">摸牌</button>
                <button id="skipBtn" onclick="skipTurn()" style="display: none;">跳过</button>
            </div>
            <button onclick="leaveRoom()" class="btn btn-danger">离开房间</button>
        </div>
    </div>

    <script>
        let stompClient = null;
        let currentRoomId = null;
        let currentPlayerId = null;
        let isRoomOwner = false;

        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 3000);
        }

        function connect() {
            if (stompClient && stompClient.connected) {
                console.log('WebSocket已连接');
                return Promise.resolve();
            }

            return new Promise((resolve, reject) => {
                let socket = new SockJS('/ws?playerId=' + currentPlayerId);
                stompClient = Stomp.over(socket);
                stompClient.debug = null; // 关闭stomp的调试日志
                
                stompClient.connect({}, function(frame) {
                    console.log('WebSocket连接成功');
                    
                    // 订阅错误消息
                    stompClient.subscribe('/user/queue/errors', function(error) {
                        console.error('收到错误消息:', error);
                        const errorData = JSON.parse(error.body);
                        showError(errorData.error);
                    });
                    resolve();
                }, function(error) {
                    console.error('WebSocket连接失败:', error);
                    showError('连接服务器失败，请刷新页面重试');
                    reject(error);
                });
            });
        }

        function startGame() {
            if (!stompClient || !stompClient.connected) {
                console.error('WebSocket未连接');
                showError('连接已断开，请刷新页面重试');
                return;
            }

            if (!currentRoomId) {
                console.error('未加入房间');
                showError('请先加入房间');
                return;
            }

            console.log('发送开始游戏请求:', {
                roomId: currentRoomId,
                playerId: currentPlayerId
            });

            try {
                stompClient.send("/app/game/start", {}, JSON.stringify({
                    roomId: currentRoomId,
                    playerId: currentPlayerId
                }));
                console.log('开始游戏请求已发送');
            } catch (error) {
                console.error('发送开始游戏请求失败:', error);
                showError('发送请求失败，请重试');
            }
        }

        function becomeDealer() {
            if (!stompClient || !stompClient.connected) {
                console.error('WebSocket未连接');
                showError('连接已断开，请刷新页面重试');
                return;
            }

            if (!currentRoomId || !currentPlayerId) {
                console.error('房间ID或玩家ID为空:', { currentRoomId, currentPlayerId });
                showError('房间信息不完整，请刷新页面重试');
                return;
            }

            console.log('准备发送抢庄请求:', {
                roomId: currentRoomId,
                playerId: currentPlayerId
            });

            try {
                stompClient.send("/app/game/become-dealer", {}, JSON.stringify({
                    roomId: currentRoomId,
                    playerId: currentPlayerId
                }));
                console.log('抢庄请求已发送');
            } catch (error) {
                console.error('发送抢庄请求失败:', error);
                showError('发送请求失败，请重试');
            }
        }

        function drawCard() {
            if (!stompClient || !stompClient.connected) {
                console.error('WebSocket未连接');
                showError('连接已断开，请刷新页面重试');
                return;
            }

            console.log('发送摸牌请求:', {
                roomId: currentRoomId,
                playerId: currentPlayerId
            });

            try {
                stompClient.send("/app/game/draw", {}, JSON.stringify({
                    roomId: currentRoomId,
                    playerId: currentPlayerId
                }));
                console.log('摸牌请求已发送');
            } catch (error) {
                console.error('发送摸牌请求失败:', error);
                showError('发送请求失败，请重试');
            }
        }

        function skipTurn() {
            if (!stompClient || !stompClient.connected) {
                console.error('WebSocket未连接');
                showError('连接已断开，请刷新页面重试');
                return;
            }

            if (!currentRoomId || !currentPlayerId) {
                console.error('房间ID或玩家ID为空:', { currentRoomId, currentPlayerId });
                showError('房间信息不完整，请刷新页面重试');
                return;
            }

            console.log('准备发送跳过请求:', {
                roomId: currentRoomId,
                playerId: currentPlayerId
            });

            try {
                stompClient.send("/app/game/skip", {}, JSON.stringify({
                    roomId: currentRoomId,
                    playerId: currentPlayerId
                }));
                console.log('跳过请求已发送');
            } catch (error) {
                console.error('发送跳过请求失败:', error);
                showError('发送请求失败，请重试');
            }
        }

        function createRoom() {
            const playerName = document.getElementById('playerName').value;
            if (!playerName) {
                showError('请输入玩家名称');
                return;
            }

            // 确保WebSocket连接
            connect().then(() => {
                fetch('/api/game/room', {
                    method: 'POST'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.error || '创建房间失败');
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    const room = data.room;
                    const player = data.player;
                    currentRoomId = room.id;
                    currentPlayerId = player.id;
                    isRoomOwner = true; // 设置房主标志
                    
                    document.getElementById('roomInfo').textContent = `房间ID: ${room.id}`;
                    document.getElementById('loginSection').style.display = 'none';
                    document.getElementById('gameSection').style.display = 'block';
                    
                    // 订阅游戏状态更新
                    if (stompClient && stompClient.connected) {
                        console.log('订阅游戏状态更新:', `/topic/game/${room.id}`);
                        stompClient.subscribe(`/topic/game/${room.id}`, function(gameState) {
                            console.log('收到游戏状态消息:', gameState);
                            const state = JSON.parse(gameState.body);
                            console.log('解析后的游戏状态:', state);
                            
                            // 添加调试信息
                            if (state.players) {
                                console.log('玩家列表:', state.players.map(p => ({
                                    id: p.id,
                                    name: p.name,
                                    isCurrentPlayer: p.currentPlayer,
                                    hasDrawn: p.hasDrawn
                                })));
                            }
                            
                            if (state.type === 'ROOM_CLOSED') {
                                showError(state.message);
                                // 重置游戏状态
                                currentRoomId = null;
                                currentPlayerId = null;
                                document.getElementById('loginSection').style.display = 'block';
                                document.getElementById('gameSection').style.display = 'none';
                                document.getElementById('roomInfo').textContent = '';
                                // 取消订阅
                                if (stompClient && stompClient.connected) {
                                    stompClient.unsubscribe(`/topic/game/${room.id}`);
                                }
                            } else {
                                // 更新房间信息显示
                                if (state.type === 'ROOM_UPDATE') {
                                    document.getElementById('roomInfo').textContent = 
                                        `房间ID: ${currentRoomId} (当前人数: ${state.players.length})`;
                                }
                                updateGameState(state);
                            }
                        });
                    } else {
                        showError('WebSocket连接已断开，请刷新页面重试');
                        return;
                    }

                    // 初始化游戏状态
                    updateGameState({
                        state: 'WAITING',
                        players: [{
                            id: player.id,
                            name: player.name,
                            cards: [],
                            dealer: false,
                            isCurrentPlayer: false,
                            score: 0
                        }]
                    });
                })
                .catch(error => {
                    showError(error.message);
                    // 确保在错误时不会进入游戏界面
                    document.getElementById('loginSection').style.display = 'block';
                    document.getElementById('gameSection').style.display = 'none';
                    // 重置状态
                    currentPlayerId = null;
                    currentRoomId = null;
                    isRoomOwner = false;
                });
            }).catch(error => {
                showError('WebSocket连接失败，请刷新页面重试');
            });
        }

        function joinRoom() {
            const playerName = document.getElementById('playerName').value;
            if (!playerName) {
                showError('请输入玩家名称');
                return;
            }

            const roomId = currentRoomId || document.getElementById('roomId').value;
            if (!roomId) {
                showError('请输入房间ID');
                return;
            }

            // 确保WebSocket连接
            connect().then(() => {
                fetch(`/api/game/room/${roomId}/join`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ name: playerName })
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.error || '加入房间失败');
                        });
                    }
                    return response.json();
                })
                .then(player => {
                    if (!player || !player.id) {
                        throw new Error('加入房间失败：服务器返回数据无效');
                    }
                    currentPlayerId = player.id;
                    document.getElementById('loginSection').style.display = 'none';
                    document.getElementById('gameSection').style.display = 'block';
                    
                    if (!currentRoomId) {
                        currentRoomId = roomId;
                        document.getElementById('roomInfo').textContent = `房间ID: ${roomId}`;
                    }
                    
                    // 订阅游戏状态更新
                    if (stompClient && stompClient.connected) {
                        console.log('订阅游戏状态更新:', `/topic/game/${roomId}`);
                        stompClient.subscribe(`/topic/game/${roomId}`, function(gameState) {
                            console.log('收到游戏状态消息:', gameState);
                            const state = JSON.parse(gameState.body);
                            console.log('解析后的游戏状态:', state);
                            
                            // 添加调试信息
                            if (state.players) {
                                console.log('玩家列表:', state.players.map(p => ({
                                    id: p.id,
                                    name: p.name,
                                    isCurrentPlayer: p.currentPlayer,
                                    hasDrawn: p.hasDrawn
                                })));
                            }
                            
                            if (state.type === 'ROOM_CLOSED') {
                                showError(state.message);
                                // 重置游戏状态
                                currentRoomId = null;
                                currentPlayerId = null;
                                document.getElementById('loginSection').style.display = 'block';
                                document.getElementById('gameSection').style.display = 'none';
                                document.getElementById('roomInfo').textContent = '';
                                // 取消订阅
                                if (stompClient && stompClient.connected) {
                                    stompClient.unsubscribe(`/topic/game/${roomId}`);
                                }
                            } else {
                                // 更新房间信息显示
                                if (state.type === 'ROOM_UPDATE') {
                                    document.getElementById('roomInfo').textContent = 
                                        `房间ID: ${currentRoomId} (当前人数: ${state.players.length})`;
                                }
                                updateGameState(state);
                            }
                        });
                    } else {
                        showError('WebSocket连接已断开，请刷新页面重试');
                        return;
                    }

                    // 初始化游戏状态
                    updateGameState({
                        state: 'WAITING',
                        players: [{
                            id: player.id,
                            name: player.name,
                            cards: [],
                            dealer: false,
                            isCurrentPlayer: false,
                            score: 0
                        }]
                    });
                })
                .catch(error => {
                    showError(error.message);
                    // 确保在错误时不会进入游戏界面
                    document.getElementById('loginSection').style.display = 'block';
                    document.getElementById('gameSection').style.display = 'none';
                    // 重置状态
                    currentPlayerId = null;
                    currentRoomId = null;
                });
            }).catch(error => {
                showError('WebSocket连接失败，请刷新页面重试');
            });
        }

        function updateGameState(gameState) {
            console.log('开始更新游戏状态:', gameState);
            document.getElementById('error').style.display = 'none';
            
            // 更新游戏状态显示
            let statusMessage = '';
            switch (gameState.state) {
                case 'WAITING':
                    statusMessage = '等待玩家加入...';
                    break;
                case 'BIDDING':
                    statusMessage = '请玩家抢庄';
                    break;
                case 'PLAYING':
                    const currentPlayer = gameState.players.find(p => p.currentPlayer === true);
                    if (currentPlayer) {
                        statusMessage = `当前回合: ${currentPlayer.name}`;
                    } else {
                        statusMessage = '等待玩家行动';
                    }
                    break;
                case 'ENDED':
                    // 找出点数最大的玩家
                    const maxPoints = Math.max(...gameState.players.map(p => p.points || 0));
                    const winners = gameState.players.filter(p => p.points === maxPoints);
                    if (winners.length === 1) {
                        statusMessage = `游戏结束 - ${winners[0].name} 获胜！`;
                    } else {
                        statusMessage = `游戏结束 - ${winners.map(w => w.name).join('、')} 平局！`;
                    }
                    break;
            }
            console.log('游戏状态更新为:', statusMessage);
            document.getElementById('gameState').textContent = `游戏状态: ${statusMessage}`;
            
            const playersDiv = document.getElementById('players');
            playersDiv.innerHTML = '';
            
            // 更新按钮状态
            const startGameBtn = document.getElementById('startGameBtn');
            const becomeDealerBtn = document.getElementById('becomeDealerBtn');
            const drawCardBtn = document.getElementById('drawCardBtn');
            const skipBtn = document.getElementById('skipBtn');
            
            // 根据游戏状态显示/隐藏按钮
            startGameBtn.style.display = isRoomOwner && gameState.state === 'WAITING' ? 'inline-block' : 'none';
            becomeDealerBtn.style.display = gameState.state === 'BIDDING' ? 'inline-block' : 'none';
            drawCardBtn.style.display = gameState.state === 'PLAYING' ? 'inline-block' : 'none';
            skipBtn.style.display = gameState.state === 'PLAYING' ? 'inline-block' : 'none';
            
            // 如果已有庄家，禁用抢庄按钮
            const hasDealer = gameState.players.some(p => p.isDealer);
            if (gameState.state === 'BIDDING' && hasDealer) {
                becomeDealerBtn.disabled = true;
            } else {
                becomeDealerBtn.disabled = false;
            }
            
            // 更新摸牌和跳过按钮状态
            if (gameState.state === 'PLAYING') {
                const currentPlayer = gameState.players.find(p => p.id === currentPlayerId);
                const isCurrentPlayer = currentPlayer && currentPlayer.currentPlayer === true;
                const hasDrawn = currentPlayer && currentPlayer.hasDrawn === true;
                
                drawCardBtn.disabled = !isCurrentPlayer || hasDrawn;
                skipBtn.disabled = !isCurrentPlayer || hasDrawn;
            }
            
            // 显示房间人数
            document.getElementById('roomInfo').textContent = `房间ID: ${currentRoomId} (当前人数: ${gameState.players.length})`;
            
            // 更新玩家列表
            gameState.players.forEach(player => {
                console.log('更新玩家信息:', player);
                const playerDiv = document.createElement('div');
                playerDiv.className = `player ${player.isDealer ? 'dealer' : 'farmer'} ${player.currentPlayer ? 'current-player' : ''}`;
                
                // 构建玩家信息显示
                let playerInfo = player.name;
                if (player.isRoomOwner) playerInfo += ' (房主)';
                if (player.isDealer) playerInfo += ' (庄家)';
                
                // 添加当前回合标记（只在游戏进行中显示）
                let turnInfo = '';
                if (gameState.state === 'PLAYING' && player.currentPlayer) {
                    turnInfo = player.hasDrawn ? 
                        '<span class="turn-status completed">已完成摸牌</span>' : 
                        '<span class="turn-status active">等待摸牌</span>';
                }
                
                // 添加胜利标签
                let winnerTag = '';
                if (gameState.state === 'ENDED' && player.points) {
                    const maxPoints = Math.max(...gameState.players.map(p => p.points || 0));
                    if (player.points === maxPoints) {
                        winnerTag = '<span class="winner-tag">胜利</span>';
                    }
                }
                
                // 构建牌面显示
                let cardsHtml = '';
                // 游戏结束时显示所有玩家的牌，否则只显示当前玩家的牌
                if (gameState.state === 'ENDED' || player.id === currentPlayerId) {
                    cardsHtml = player.cards.map(card => {
                        // 将花色转换为小写并添加类名
                        const suitClass = card.suit.toLowerCase();
                        // 使用HTML实体来显示花色符号
                        const suitSymbol = {
                            'hearts': '♥',
                            'diamonds': '♦',
                            'clubs': '♣',
                            'spades': '♠'
                        }[suitClass] || card.suit;
                        return `<div class="card ${suitClass}">${suitSymbol}${card.value}</div>`;
                    }).join('');
                    if (cardsHtml === '') {
                        cardsHtml = '<div class="card-count">暂无手牌</div>';
                    }
                } else {
                    // 其他玩家的牌（显示牌背）
                    const cardCount = player.cards ? player.cards.length : 0;
                    cardsHtml = `<div class="card-count">手牌数量: ${cardCount}</div>`;
                    for (let i = 0; i < cardCount; i++) {
                        cardsHtml += `<div class="card card-back"><div class="card-back-inner"></div></div>`;
                    }
                }
                
                // 构建点数显示（游戏结束时显示所有玩家的点数）
                let pointsHtml = '';
                if (gameState.state === 'ENDED' || player.id === currentPlayerId) {
                    pointsHtml = `<div class="points">点数: ${player.points || 0}</div>`;
                }
                
                playerDiv.innerHTML = `
                    <h3>${playerInfo} ${turnInfo} ${winnerTag}</h3>
                    <div class="cards">${cardsHtml}</div>
                    ${pointsHtml}
                `;
                playersDiv.appendChild(playerDiv);
            });
            
            console.log('游戏状态更新完成');
        }

        function leaveRoom() {
            if (!currentRoomId) {
                showError('未加入任何房间');
                return;
            }

            fetch(`/api/game/room/${currentRoomId}/leave`, {
                method: 'POST'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.error || '离开房间失败');
                    });
                }
                // 重置游戏状态
                currentRoomId = null;
                currentPlayerId = null;
                isRoomOwner = false;
                document.getElementById('loginSection').style.display = 'block';
                document.getElementById('gameSection').style.display = 'none';
                document.getElementById('roomInfo').textContent = '';
                
                // 取消订阅但不断开连接
                if (stompClient && stompClient.connected) {
                    stompClient.unsubscribe(`/topic/game/${currentRoomId}`);
                }
            })
            .catch(error => {
                showError(error.message);
            });
        }

        // 添加页面离开提示
        window.onbeforeunload = function() {
            if (currentRoomId) {
                return "确定要退出房间吗？";
            }
        };

        // 添加页面可见性变化监听
        document.addEventListener('visibilitychange', function() {
            if (document.visibilityState === 'visible') {
                // 页面变为可见时，检查连接状态
                if (!stompClient || !stompClient.connected) {
                    console.log('页面可见，重新连接WebSocket');
                    connect();
                }
            }
        });

        // 页面加载时建立WebSocket连接
        connect().catch(error => {
            console.error('初始连接失败:', error);
            setTimeout(connect, 5000); // 5秒后重试
        });
    </script>
</body>
</html> 